/*
	author: kapil kashyap
 */
dynamicSearch = (function($) {
	// Global variables
	var config = {
			relativeTo: '#apply-dynamic-search', // mandatory to pass the CSS selector of the table if it is other than the default value
			searchBoxPosition: null, // can take - top/right/bottom/left/top-right/bottom-right/bottom-left/top-left values
			searchBoxMargins: null,
			searchCmpId: 'dynamic-search-container',
			searchInputId: 'dynamic-search-text',
			searchContainerCls: '',
			events: ['keyup', 'focus']
		},
		action = 'highlight',
		messageId = 'message',
		noMatchFoundMessage =  function(colSpan) {
			var $elementTr = $('<tr></tr>'),
				$elementTd = $('<td></td>');
			
			$elementTr.attr('id', messageId);
			$elementTd.attr('colspan', colSpan);
			$elementTr.html( $elementTd.html('No matches found.') );
			
			return $elementTr;
		},
	
		searchEventHandler = function(event) {
			// Remove the message row from the table if found.
			if($( '#' + messageId ).length > 0) {
				$( '#' + messageId ).remove();
			}
			
			var text = $.trim( $( '#' + config.searchInputId ).val() ).toLowerCase(),
				$rowObjects = $( config.relativeTo ).find( 'tbody:first > tr' ),
				rowCounter = 0,
				$cells = null;
			
			$rowObjects.each(function(index, $row) {
				var matchFound = false;
					
				$cells = $row.cells;
				
				$($cells).each(function(index, $cell) {
					// object.textContent is not supported in IE8. Instead use object.innerText.
					var _innerHtml = ($cell.textContent ? $cell.textContent : $cell.innerText).toLowerCase();
					if(_innerHtml.match(text) != null) {
						matchFound = true;
					}
				});
				
				$( $row ).show();
				if(action == 'toggle') {
					if(!matchFound) {
						$( $row ).hide();
						rowCounter++;
					}
					else {
						$( $row ).css('background-color', '#ffffff');
					}
				}
				else if(action == 'highlight') {
					if(matchFound && text != '') {
						$( $row ).css('background-color', '#fff990');
					}
					else {
						$( $row ).css('background-color', '#ffffff');
					}
				}
			});
			
			// Inserting a message row if there is no match found.
			if(action == 'toggle' && rowCounter == $rowObjects.length) {
				$( config.relativeTo ).find( 'tbody:first' ).append( noMatchFoundMessage( $cells.length ) );
			}
			
			$( '#' + config.searchCmpId ).reposition( config.relativeTo, config.searchBoxPosition, config.searchBoxMargins); //[-1,0,0,2]  
		};
		
		return {
			initialize: function( _config ) {
				$.extend(config, _config);
				
				// checking if component reposition plugin is also included.
				if(!$( '#' + config.searchCmpId ).reposition) {
					var errorMsg = 'component-reposition-plugin is required.';
					if(window.console) {
						console.error ? console.error( errorMsg ) : console.log( errorMsg );
					}
					else {
						alert( errorMsg );
					}
					return;
				}
				
				var searchCmp = $( 
						'<div id="' + config.searchCmpId + '" class="' + config.searchContainerCls + '">' +
							'Search:&nbsp;' +
							'<input type="text" id="' + config.searchInputId + '" name="search" size="15" value=""/>' +
							'<input type="radio" id="highlightRadio" name="action" value="highlight" checked="checked">Highlight</input>' +
							'<input type="radio" id="toggleRadio" name="action" value="toggle">Toggle</input>' +
						'</div>'
					),
					inputElements = searchCmp.find( ':radio' ),
					searchBoxElement = searchCmp.find( '#' + config.searchInputId );
					
				// appending the search component to the body.
				$( 'body' ).append( searchCmp );
				
				// attaching events to the searchText input box.
				$.each(config.events, function(key, event) {
					searchBoxElement[event](searchEventHandler);
				});

				inputElements.each(function(index, element) {
					$(element).click(function() {
						action = $( this ).val();
						$( '#' + config.searchInputId ).focus();
					});
				});
				
				$( document ).keydown( function( e ) {
					// close on Esc key press
					if(e.which == 27) {
						$( '#' + config.searchInputId ).val('');
						$( '#highlightRadio' ).click();
						$( '#' + config.searchCmpId ).hide();
						
						e.stopPropagation();
					}
					
					if(e.ctrlKey && e.altKey && e.which == 83) {
						$( '#' + config.searchCmpId ).reposition( config.relativeTo, config.searchBoxPosition, config.searchBoxMargins);
						$( '#' + config.searchCmpId ).show();
						$( '#' + config.searchInputId ).focus();
					}
				});
			}
		};
})(jQuery);
